local newt = reload("newt")
local delt = reload("delt")
local delts = reload("delts")
local class = reload("class")
local super = reload("super.basic")
local sqlite3C = require("sqlite3C")

---@class sqlite3LC : super.basic
local this = class(super)

function this:ctor(name, info)
    super.ctor(self)
    self._name = name
    self._info = info
end

function this:launch()
    local info = self._info
    ---直接返回是否链接成功
    return sqlite3C.new(self._name, info.db, self)
end

function this:selectpush(fields, rows)
    if fields and rows then
        local col = #fields
        for _, row in ipairs(rows) do
            for i = 1, col do
                local key = fields[i]
                local val = row[i]
                row[i] = nil
                row[key] = val
            end
        end
        delt(fields)
    end
    return rows
end

function this:insert(sql, ...)
    assert(self._info.write or false, "没有写入权限")
    return sqlite3C.insert(self._name, sql, ...)
end

function this:update(sql, ...)
    assert(self._info.write or false, "没有写入权限")
    return sqlite3C.update(self._name, sql, ...)
end

function this:delete(sql)
    assert(self._info.write or false, "没有写入权限")
    return sqlite3C.delete(self._name, sql)
end

function this:select(sql)
    local fields, rows = sqlite3C.select(self._name, sql)
    return self:selectpush(fields, rows)
end

function this:rowfmt(fmt, tb, where)
    local sql = fmt:format(tb, where)
    local rows = self:select(sql)
    local row = rows[1]
    return row.cnt
end

---获取表的行数
function this:rowcnt(tb, where)
    if where then
        local fmt = [[select count(1) as cnt from %s where %s;]]
        return self:rowfmt(fmt, tb, where)
    else
        local fmt = [[select count(1) as cnt from %s;]]
        return self:rowfmt(fmt, tb, where)
    end
end

function this:create(sql)
    assert(self._info.write or false, "没有写入权限")
    return sqlite3C.create(self._name, sql)
end

function this:drop(sql)
    assert(self._info.write or false, "没有写入权限")
    return sqlite3C.drop(self._name, sql)
end

function this:alter(sql)
    assert(self._info.write or false, "没有写入权限")
    return sqlite3C.alter(self._name, sql)
end

function this:truncate(sql)
    assert(self._info.write or false, "没有写入权限")
    return sqlite3C.truncate(self._name, sql)
end

function this:close()
    return sqlite3C.close(self._name)
end

--垃圾回收
function this:gcback()
    self:close()
    super.gcback(self)
end

return this
